﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Print(string str)
        {
            BeginInvoke(new Action(() =>
            {
                this.textBox1.AppendText(str + "\n");
            }));
        }

        

        private void Run1()
        {
            for (int i = 0; i < 3; i++)
            {
                Print(DateTime.Now.ToString());
                Thread.Sleep(1000);
            }
            Print("child thread done");
        }

        private string Run2()
        {
            int res=0;
            for (int i = 0; i < 3; i++)
            {
                Print(DateTime.Now.ToString());
                res+=i;
                Thread.Sleep(1000);
            }
            Print("child thread done");
            return res.ToString();
        }

        private async Task Run3()
        {
            Print("child thread run");
            await Task.Delay(1000);
            Print("child thread done");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.textBox1.Clear();
            Task task = new Task(Run1);
            task.Start();
            Print("Main thread done");
            //Console.ReadLine();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //要在主线程中等待后台线程执行完毕，可以使用Wait方法(会以同步的方式来执行)。不用Wait则会以异步的方式来执行。
            this.textBox1.Clear();
            Task task = new Task(Run1);
            
            task.Start();
            task.Wait();
            Print("Main thread done");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.textBox1.Clear();
            Task task = new Task(Run1);
            Print("Before start: " + task.Status);
            task.Start();
            Print("After start: " + task.Status);
            task.Wait();//(阻塞)
            Print("After Finish: " + task.Status);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.textBox1.Clear();
            Task<string> task = new Task<string>(Run2);
            task.Start();
            Print("result:" + task.Result);//通过task.Result可以取到返回值，若取值的时候，后台线程还没执行完，则会等待其执行完毕！(阻塞)
            Print("Main thread done");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Run3();
        }
    }
}
